package com.vanEngine.managers
{
	import com.vanEngine.errors.SingletonInstantiationErr;
	
	import flash.display.InteractiveObject;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.FocusEvent;

	/**
	 * 焦点管理器, 用于防止焦点对象从舞台中删除后,失焦的情况 
	 * @author ZhongZw
	 * 
	 */	
	public class FocusManager
	{
		private var _stage:Stage;
		private var _curFocusObj:InteractiveObject;
		private static var _instance:FocusManager;
		
		public function FocusManager()
		{
			if( _instance ) throw new SingletonInstantiationErr();
		}
		
		public static function instance():FocusManager
		{
			if( !_instance )
			{
				_instance = new FocusManager();
			}
			
			return _instance;
		}
		
		public function initStage(stage:Stage) : void
		{
			if( !_stage ) return;
			
			this._stage = stage;
			
			this._stage.addEventListener(FocusEvent.FOCUS_IN, onFocusInHandler);
			
			curFocusObj = this._stage;
			
		}
		
		private function onFocusInHandler(event:FocusEvent) : void
		{
			curFocusObj = event.target;
		}
		
		public function set curFocusObj( obj:InteractiveObject ):void
		{
			if( !_stage ) return;
			
			if( _curFocusObj && _curFocusObj != _stage )
			{
				_curFocusObj.removeEventListener(Event.REMOVED_FROM_STAGE, onRemoveFromStageHandler);
			}
			
			_curFocusObj = obj;
			
			if( obj && obj != _stage )
			{
				obj.addEventListener( Event.REMOVED_FROM_STAGE, onRemoveFromStageHandler );
			}
			
			this._stage.focus = _curFocusObj;
		}
		
		public function get curFocusObj() : InteractiveObject
		{
			return this._curFocusObj;
		}
		
		private function onRemoveFromStageHandler(event:Event) : void
		{
			curFocusObj = _stage;
		}
		
	}
}